<?php

namespace app\api\controller\v45;

use app\aliyun\controller\AliyunFilterWordV2;
use app\api\controller\v2\Auth;
use app\common\cachemodel\AppConfig;
use app\common\cachemodel\chat\HzChatRecord;
use app\common\cachemodel\chat\HzChatRecordDetails;
use app\common\lib\Util;
use app\common\model\Recode;
use think\Log;

class AiUserChat extends Auth
{
    public function diceQuestion()
    {
        $question = input('question/s', '');
        $rid = input('rid/d', 0);
        $gptModel = input('model/s', '');  // 会话模型

        if (Util::commentCheck($this->user['id'], ['action' => 'divinationQuestion', 'question' => $question, 'rid' => $rid, 'model' => $gptModel], 5) && (int)$this->user['id'] != 10834769)
        {//mark 17333657763 手机号的uid为10834769，可以测试并发
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        if (empty($question))
        {
            return show(config('code.error'), '请输入提问的内容');
        }
        if (mb_strlen($question) > 40)
        {
            return show(config('code.error'), '问题最多40字');
        }
        $aliRes = AliyunFilterWordV2::checkAIText($question);
        if ($aliRes['status'] === false)
        {
            return show(0, '检测到敏感内容');
        }
        if ($rid)
        {
            $recodeInfo = (new Recode())->getRecode(['id' => $rid]);
            if (!$recodeInfo || $recodeInfo['uid'] != $this->user['id'] || $recodeInfo['status'] != 1)
            {
                return show(config('code.error'), '档案不存在');
            }
        } else
        {
            $rid = (int)($this->user['rid'] ?? 0);
        }
        $hzChatRecordModel = new HzChatRecord();
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);
        if ($numData['res_num'] <= 0)
        {   // 会话次数 用尽
            $msg = $numData['vip_level'] > 0 ? '今日提问机会用尽，明天再来吧～' : '提问机会用尽，请开通会员或购买';
            return show(config('code.error'), $msg);
        }
        // 通过rid 取当前会话ID
        if ($rid)
        {
            $chatId = $hzChatRecordModel->getChatIdByRid($rid);
        } else
        {
            $chatId = $hzChatRecordModel->getChatIdByUid($this->user['id']);
        }
        if (!$chatId)
        {
            return show(config('code.error'), '服务异常，请刷新页面重试～');
        }
        $nowTimw = $this->request->time();
        // 安卓端在塔罗开发版本时，纬度和时区字段两个值传反了，特殊处理
        $_arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 16];// 行星id随机数种子`
        $data['planet'] = $_arr[rand(0, count($_arr) - 1)];
        $data['sign'] = rand(1, 12);
        $data['house'] = rand(1, 12);
        try
        {
            if (Util::isOnline())
            {   // 线上环境
                $chatConfig = (new AppConfig())->configInfo('chat_config');
                $gptModel = $chatConfig['gpt_model_name'] ?? '';
            }
            // 扣除次数
            $numData = $hzChatRecordDetailsModel->chatQueryEndNumDec($this->user['id'], $numData);
            $extend = [
                'result_type' => 2,
                'model_name' => $gptModel,
                'is_valid' => 1,
                'stream' => 1,
                'sas' => 3, // 语义解析集群分类场景结果 0为专业场景，1为基础场景，2为拒答场景 3未进行语义解析之间进行骰子获取结果
                'sact' => [],
                'dice_info' => [
                    'question' => $question,
                    'planet' => $data['planet'],
                    'sign' => $data['sign'],
                    'house' => $data['house'],
                    'id' => 0,
                    'answer_type' => 2,
                    'answer_content' => '',
                ],
            ];
            $insertData = [
                [   // 用户提问消息
                    'chat_id' => $chatId,
                    'uid' => $this->user['id'],
                    'rid' => $rid,
                    'type' => 2,    //  1=>APP消息 2=>用户发送消息
                    'title' => '',
                    'content' => $question, // 提问问题
                    'data_type' => 1,
                    'extend' => [],
                    'result_data' => '',
                    'option_id' => '',
                    'pid' => 0,
                    'create_time' => $nowTimw,
                ], [    // 骰子结果信息
                    'chat_id' => $chatId,
                    'uid' => $this->user['id'],
                    'rid' => $rid,
                    'type' => 1,    //  1=>APP消息 2=>用户发送消息
                    'title' => '',
                    'content' => '', // 提问问题
                    'data_type' => 3,   // 1=>普通消息  2=>结果消息 3=>扩展消息'
                    'extend' => $extend,  //  澄清数据
                    'result_data' => '',
                    'option_id' => '',
                    'num_type' => $numData['use_type'], // 使用类型 1=免费次数 2=>vip次数 3=>购买次数 4=>赠送次数
                    'pid' => 0, // 待更新
                    'create_time' => $nowTimw,
                ],
            ];
            $resInsertData = $hzChatRecordDetailsModel->SaveData($chatId, $insertData);
            $resData = $hzChatRecordDetailsModel->dataListResert($resInsertData, true);
            $resData[1]['create_time'] = '';
            $resData[1]['stream'] = 1;
            $resData[1]['is_stream_reload'] = 0;
            return show(config('code.success'), '请求成功', [
                'num' => $numData['res_num'],
                'input_text' => $hzChatRecordDetailsModel->getInputPlaceholder($numData),
                'list' => $resData,
            ]);
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }
}
